import 'package:mobx/mobx.dart';
import '../models/video_model.dart';
import '../services/video_service.dart';
import 'auth_store.dart';

part 'video_store.g.dart';

class VideoStore = _VideoStore with _$VideoStore;

abstract class _VideoStore with Store {
  final VideoService _videoService = VideoService();
  final AuthStore _authStore;

  _VideoStore(this._authStore);

  @observable
  ObservableList<VideoModel> videos = ObservableList<VideoModel>();

  @observable
  VideoModel? currentVideo;

  @observable
  bool isLoading = false;

  @observable
  String? errorMessage;

  @computed
  List<VideoModel> get collectedVideos {
    return videos.where((video) => video.isCollected).toList();
  }

  @action
  Future<void> loadVideos() async {
    isLoading = true;
    errorMessage = null;

    try {
      final allVideos = _videoService.getAllVideos();
      videos.clear();
      videos.addAll(allVideos);
      isLoading = false;
    } catch (e) {
      errorMessage = 'Load videos failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<void> createSampleVideos() async {
    isLoading = true;
    errorMessage = null;

    try {
      await _videoService.addSampleVideos();
      await loadVideos();
      isLoading = false;
    } catch (e) {
      errorMessage = 'Add sample videos failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<void> toggleVideoCollected(String videoId) async {
    if (_authStore.currentUser == null) return;

    try {
      final videoIndex = videos.indexWhere((v) => v.id == videoId);
      if (videoIndex >= 0) {
        final video = videos[videoIndex];
        final newState = !video.isCollected;

        await _videoService.toggleCollected(videoId, newState);

        // 更新本地状态
        videos[videoIndex] = _videoService.getVideoById(videoId)!;

        // 如果当前视频是被修改的视频，也更新它
        if (currentVideo?.id == videoId) {
          currentVideo = _videoService.getVideoById(videoId);
        }
      }
    } catch (e) {
      errorMessage = 'Update video collection status failed: ${e.toString()}';
    }
  }

  @action
  void selectVideo(String videoId) {
    currentVideo = _videoService.getVideoById(videoId);
  }

  @action
  Future<List<VideoModel>> searchVideos(String query) async {
    isLoading = true;
    errorMessage = null;

    try {
      final results = _videoService.searchVideos(query);
      isLoading = false;
      return results;
    } catch (e) {
      errorMessage = 'Search videos failed: ${e.toString()}';
      isLoading = false;
      return [];
    }
  }
}
